package com.teamwhole.modules.sys.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.teamwhole.common.config.Global;
import com.teamwhole.common.utils.FileUpload;
import com.teamwhole.common.utils.StringUtils;
import com.teamwhole.modules.report.entity.ScoreReport;
import com.teamwhole.modules.sys.entity.Attachment;
import com.teamwhole.modules.sys.entity.AttachmentInfo;
import com.teamwhole.modules.sys.service.AttachmentInfoService;

@Path("/sys/file")
//@Produces("application/json;charset=utf-8")
public class FileUploadResource {
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private AttachmentInfoService ais;

	@Context
	private HttpServletResponse response;

	@Path("upload")
	@POST
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	@Produces(MediaType.TEXT_PLAIN)
	public Response uploadFile(FormDataMultiPart fdmp) {
		// 文件名
		String name = fdmp.getField("name").getValue();
		String type = fdmp.getField("type").getValue();
		FileUpload fileUpload = new FileUpload(type);
		String[] result = fileUpload.upload(fdmp);

		if (result != null) {
			if (StringUtils.isBlank(name)) {
				name = result[0]; // 取原始文件名
			}

			Attachment attachment = new Attachment();
			attachment.setTypeCode(type);
			attachment.setName(name);

			AttachmentInfo info = new AttachmentInfo();
			info.setFilePath(result[2]);
			info.setFileName(result[1]);
			info.setFileExt(name.substring(name.lastIndexOf(".") + 1));
			info.setAttachment(attachment);
			ais.save(info);
			
			return Response.status(200).entity(info.getFilePath()).build();
		}
		return null;
	}

//	@Path("get")
//	@GET
//	@Produces({ "image/*", MediaType.APPLICATION_OCTET_STREAM })
//	public Response get(@QueryParam("id") String id) {
//		if (StringUtils.isNotBlank(id)) {
//			AttachmentInfo info = ais.get(id);
//			if (info != null) {
//				return download(info.getFileName(), info.getFileExt(), info.getFilePath());
//			}
//		}
//		return Response.noContent().build();
//	}
	
	@Path("get")
	@GET
	@Produces({"image/png", "image/jpg","image/jpeg", "image/gif", MediaType.APPLICATION_OCTET_STREAM})
	public Response get(@QueryParam("path") String path) {
		if (StringUtils.isNotBlank(path)) {
			String[] pathArr = path.split("\\\\");
			String fileName = pathArr[pathArr.length - 1];
			return download(fileName, fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(), path);
		}
		return Response.noContent().build();
	}
	
	public Response download(String fileName, String fileExt, String path) {
		try {
			String dirPath = Global.getConfig("dirPath");
			StringBuilder sb = new StringBuilder(dirPath);
			sb.append(File.separator);
			sb.append(path);
			
			File file = new File(sb.toString());
			if (file.exists()) {
				InputStream in = new FileInputStream(file);
				return isImage(fileExt) ? Response.ok(in).build()
						: Response.ok(in, MediaType.APPLICATION_OCTET_STREAM)
								.header("content-disposition", "attachment; filename = " + fileName).build();
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return Response.noContent().build();
	}

	private Boolean isImage(String fileExt) {
		String ext = "gif,jpg,jpeg,png,bmp";
		return Arrays.<String> asList(ext.split(",")).contains(fileExt);
	}
	@Consumes("application/json;charset=utf-8")
	@Produces({ MediaType.APPLICATION_OCTET_STREAM})
	@Path("ExportExcel")
	@POST
	public Response ExportExcel(ScoreReport map) {
		String filedata=map.getGridID();//"a.xls";
		String filename=map.getGridName();//"<table><tr><td>asdfasfasf</td><td>asdfasfasf</td></tr></table>";
		return Response.ok((Object)filedata)
				.header("content-disposition", "attachment;charset=utf-8; filename =  "+filename ).build();
	}
}